package io.adrainty.bolee.security.repository.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.adrainty.bolee.framework.commons.user.UserEntity;
import io.adrainty.bolee.security.mapper.ICustomerMapper;
import io.adrainty.bolee.security.models.bo.CustomerBO;
import io.adrainty.bolee.security.repository.ICustomerRepository;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/8/3 上午1:04
 */

@Repository
public class CustomerRepositoryImpl implements ICustomerRepository {

    @Resource
    private ICustomerMapper customerMapper;

    @Override
    public UserEntity findByUsername(String username, String company) {
        if (StringUtils.isBlank(username)) return null;
        Wrapper<CustomerBO> wrapper = Wrappers.lambdaQuery(CustomerBO.class)
                .eq(CustomerBO::getUsername, username)
                .eq(CustomerBO::getCompanyNo, company);
        CustomerBO selectOne = customerMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }

    @Nullable
    @Override
    public UserEntity findByMobile(String mobile, String company) {
        if (StringUtils.isBlank(mobile)) return null;
        Wrapper<CustomerBO> wrapper = Wrappers.lambdaQuery(CustomerBO.class)
                .eq(CustomerBO::getMobile, mobile)
                .eq(CustomerBO::getCompanyNo, company);
        CustomerBO selectOne = customerMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }

    @Nullable
    @Override
    public UserEntity findByOpenId(String openId, String company) {
        if (StringUtils.isBlank(openId)) return null;
        Wrapper<CustomerBO> wrapper = Wrappers.lambdaQuery(CustomerBO.class)
                .eq(CustomerBO::getOpenId, openId)
                .eq(CustomerBO::getCompanyNo, company);
        CustomerBO selectOne = customerMapper.selectOne(wrapper);
        if (selectOne == null) return null;
        return BeanUtil.copyProperties(selectOne, UserEntity.class);
    }
}
